﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UFramework.Tools
{
    public class UnitySingleton<T> : MonoBehaviour where T : UnitySingleton<T>
    {
        private static T _instance;

        public static T Instance
        {
            get
            {
                //先找下场景中有没有
                if (_instance == null)
                {
                    _instance = FindObjectOfType<T>();
                }

                //如果没找到就创建
                if (_instance == null)
                {
                    _instance = new GameObject("@" + typeof(T).Name).AddComponent<T>();
                }
                return _instance;
            }
        }

        protected virtual void Awake()
        {
            if (_instance == null)
            {
                _instance = this as T;
            }
            else
            {
                if (_instance != this)
                {
                    UnityEngine.Debug.Log("存在两个单例对象:" + typeof(T).Name);
                }
            }

            Init();
        }

        protected virtual void Init()
        {
        }

        private void Reset()
        {
            this.name = "@" + typeof(T).Name;
        }
    }
}